import React, { useEffect, useMemo, useState } from 'react'
import styles from './msg.module.css'
import { TextArea, Button } from 'antd-mobile'

function Index() {
  //1.声明用户Id 和 服务 Id
  const user_id = 1;
  const server_id = 520;

  const ws = useMemo(() => {
    return new WebSocket(
      `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
    );
  }, [])

  const [message, setMessage] = useState('')
  const [chatList, setChatList] = useState([])

  useEffect(() => {
    ws.onopen = () => {
      console.log('连接成功');
      ws.send(JSON.stringify({ type: 'getChatList' }));
    };
    ws.onmessage = (msg) => {
      console.log(JSON.parse(msg.data))
      const { type, data } = JSON.parse(msg.data)
      if (type === 'getChatList') {
        setChatList(data)
      } else if (type === 'addMessage') {
        setChatList((pre) => [...pre, data])
      }
    }
  }, [])
  // 发送消息
  const handleSend = () => {
    ws.send(
      JSON.stringify({
        type: 'addMessage',
        data:{
          user_id,
          server_id,
          message
        }
      }));
      setMessage('')
  }

  return (
    <div>

      <div className={styles.msgBox}>
        {/* 放聊天记录 */}
        <div className={styles.chatList}>
          {
            chatList.map((item, index) => {
              const classItem = `chat-list-${item.dir === 1 ? 'left' : 'right'}`;
              const avatar = item.dir === 1 ? 'https://avatars.githubusercontent.com/u/33021497?s=40&v=4':item.user_avatar;
              return <div key={index} className={styles[classItem]}>
                {/* 头像 */}
                <div>
                  <img style={{ width: '40px', height: '40px', borderRadius: '50%' }} src={avatar} alt="" />
                </div>
                <div >
                  <div className={styles.text} >{item.message}</div>
                </div>
              </div>
            })
          }
        </div>
        {/* 底部发送消息 */}
        <div className={styles.chatFoot}>
          <div>
            <span className={styles.emljoFz}>🥲</span>
          </div>
          <TextArea
            placeholder='请输入内容'
            value={message}
            onChange={val => {
              setMessage(val)
            }}
          />
          <Button size='mini' color='primary' onClick={() => handleSend()}>
            发送
          </Button>
        </div>
      </div>

    </div>
  )
}

export default Index
